<?
$expire=time()+60*60*3;
if(!isset($_COOKIE["boughttotal"])) {
    setcookie("boughttotal", "", $expire);
}

if(!$_POST["clear_cart"]==0) {
    logout();
}

if(!$_POST["make_changes"]==0) {
    makeChanges();
}
// VARS
$buttonnamesarray = array();
// END OF VARS

function addToCart() {
    #adding to cart
    if(!$_POST["buybutton"]==0) {
        $idproduct = $_POST["buybutton"][strlen($_POST["buybutton"])-1];
        if($_COOKIE["boughttotal"] == "") {
            setcookie("boughttotal", $idproduct, $expire);
        }
        else {
            $boughtpreviouslyarray=array();
            $boughtpreviouslyarray[0] = $_COOKIE["boughttotal"];
            $boughtpreviouslyarray[1] = $idproduct;
            $boughtnew = implode(",", $boughtpreviouslyarray);
            setcookie("boughttotal", $boughtnew, $expire);
        }
    }
}

addToCart();

$baseArray=array();

function selectAll () {
    ### SECURED INFORMATION HAZARD!
    $sqlConnect=mysql_connect('localhost', 'root', 'kissakala');
    ### END OF SECURED INFORMATION
    mysql_select_db('theshop', $sqlConnect);
    $sqlQuery="SELECT * FROM products";
    $sqlResult=mysql_query($sqlQuery, $sqlConnect);
    $i =-1;
    while($sqlRow=mysql_fetch_array($sqlResult, MYSQL_ASSOC)) {
        $i++;
        $row=$sqlRow['prodNo'];
        $name=$sqlRow['prodName'];
        $picture=$sqlRow['prodPic'];
        $desc=$sqlRow['prodDesc'];
        $value=$sqlRow['prodValue'];
        $amount=$sqlRow['prodAmount'];
        $ship=$sqlRow['prodShip'];
        $baseArray[$i]=array();
        $baseArray[$i][0]=$row;
        $baseArray[$i][1]=$picture;
        $baseArray[$i][2]=$name;
        $baseArray[$i][3]=$desc;
        $baseArray[$i][4]=$value;
        $baseArray[$i][5]=$amount;
        $baseArray[$i][6]=$ship;
    }
    return $baseArray;
}

function  outputCart($array, $mode) {

    if(!$_COOKIE["boughttotal"] == "") {


        $comma_separated = explode(',', $_COOKIE["boughttotal"]);
        $theLength=count($comma_separated);
        $alreadyOutputed = array();
        $totalPrice = 0;

        //OUTPUTTING
        $number = 0;
        $j = 0;
        echo "<table id=\"layouttable\"><tr><td><h4>Items in basket:</h4></td></tr></table>";
        for ($i = 0; $i < $theLength; $i++) {
            if (!in_array($comma_separated[$i]-1, $alreadyOutputed)) {
                echo "<table  width=100% id=\"itemtable\"><tr>";
                echo "<td id=\"itemname\">";
                echo $array[$comma_separated[$i]-1][2];
                $number = howMany($comma_separated[$i],$comma_separated);
                //TODOOO forms
                $nameEditForm = "form_".$array[$comma_separated[$i]-1][0];
                echo "</td><td id=\"itemnumber\"> ".$number."";
                echo "</td><td id=\"itemprice\">";
                echo $number*$array[$comma_separated[$i]-1][4];
                echo "</td></tr>";
                array_push($alreadyOutputed, $comma_separated[$i]-1);
                $totalPrice += $number*$array[$comma_separated[$i]-1][4];
            }
        }
        //TODOOO
        echo "<tr><td></td><td>Total price:</td><td><b>";
        echo $totalPrice;
        echo "</b></td></tr>";
        echo "</table>";
        if ($mode==1) {
            echo "<table width=\"100%\"><tr><td><form name=\"clearcart\" action=\"cart.php\" method=\"POST\"><input type=\"submit\" value=\"clear cart\" name=\"clear_cart\" class=\"clearcartbutton\" /></form></td><td><form name=\"checkout\" action=\"checkout.php\" method=\"POST\"><input type=\"submit\" value=\"Checkout\" name=\"checkout\" class=\"checkoutbutton\"\"/></form></td></tr></table>";
            $_SESSION['emptyit'] = 'empty';
        }
    }
    else {
        echo "<table id=\"layouttable\"><tr><td>Your shopping cart is empty. Go buy something! (or refresh the page)</td</tr></table>";
    }
}

function howMany($needle,$haystack) {
    $exists = array_search($needle,$haystack);
    //if the desired element exists in the array
    if ($exists !== FALSE)
    //return 1 and call the function again with the array after the
    //first occurance of needle
        return 1 + howMany($needle,array_slice($haystack,($exists+1)));

    //if the element does not exist return 0;
    return 0;
} //end howMany

function layoutTable ($array, $buttonurl1, $buttonurl2, $pageCalled, $page=1) {
    echo "<table width=98% id=\"layouttable\"  cellspacing=\"0\" cellpadding=\"0\">";
    $theLength=count($array);
    $theLengthProd = count($array[0]);
    #defining start and end items for outputting in pages
    if ($page>0) {
        $startItem = ($page-1)*10;
        if($startItem+10 < $theLength) {
            $endItem = $startItem+10;
        }
        else {
            $endItem = $theLength;
        }
    }
    else {
        $startItem = 0;
        $endItem = $theLength;
    }
    for ($i = $startItem; $i < $endItem; $i++) {
        echo "<tr><td>";
        echo "<table  width=100% id=\"itemtable\"><tr><td id=\"itempic\">";
        $itemurl = "item.php?id=".$array[$i][0];
        $picture="<a href=\"".$itemurl."\"><img src=\"".$array[$i][1]."\"/></a>";
        echo $picture;
        echo "</td><td id=\"itemcol2\">";

        echo "<table id=\"itemdesc\"><tr><td id=\"itemname\"><a href=\"".$itemurl."\">";
        echo $array[$i][2];
        echo "</a>";
        echo " (#";
        echo $array[$i][0];
        echo ")";
        echo "</td><td id=\"itemprice\">";
        echo $array[$i][4];
        echo "&euro;</td></tr>";

        echo "<tr><td colspan=\"2\">";
        echo $array[$i][3];
        echo "</td></tr>";
        echo "<tr><td id=\"buybutton1\">";
        echo "</td><td id=\"buybutton2\">";
        $buttonnamearray=array();
        $buttonnamearray[0] = "buybutton";
        $buttonnamearray[1] = $i+1;
        $buybuttonname = implode("_", $buttonnamearray);
        $buttonnamesarray += $buybuttonname;
        echo "<form action=\"products.php\" method=\"post\">";
        echo "<input type=\"submit\" value=\"".$buybuttonname."\" name=\"buybutton\" class=\"buybutton\"/></form>";
        echo "</td></tr></table>";
        echo "</td></tr></table>";
        echo "</tr>";
    }
    echo "</table>";
    if ($page!=1) {
        $previousPage = $page-1;
        echo "<a href=\"".$pageCalled."?page=".$previousPage."\">Previous page</a>";
    }
    if ($endItem != $theLength) {
        $nextPage = $page+1;
        if ($page != 1) {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        echo "<a href=\"".$pageCalled."?page=".$nextPage."\">Next page</a>";
    }
}

function showItem($array, $itemid, $buttonurl1, $buttonurl2, $type=1) {
    echo "<table width=98% id=\"layouttable2\"  cellspacing=\"0\" cellpadding=\"0\">";
    $i = $itemid-1;
    echo "<tr><td>";
    echo "<table  width=100% id=\"itemtable\"><tr><td id=\"itempic\">";
    $itemurl = "item.php?id=".$array[$i][0];
    $picture="<a href=\"".$itemurl."\"><img src=\"".$array[$i][1]."\"";
    echo $picture;
    if ($type==2) {
        echo " HEIGHT=\"50\", WIDTH=\"40\" ";
    }
    echo "/></a>";
    echo "</td><td id=\"itemcol2\">";
    echo "<table id=\"itemdesc\"><tr>";
    echo "<td id=\"itemname\">";
    if ($type==2) {
        echo "<a href=\"".$itemurl."\">";
        echo $array[$i][2];
        echo "</a>";
    }
    else {
        echo $array[$i][2];
    }
    echo " (#";
    echo $array[$i][0];
    echo ")";
    echo "</td><td id=\"itemprice\">";
    echo $array[$i][4];
    echo "&euro;</td></tr>";

    echo "<tr><td colspan=\"2\">";
    echo $array[$i][3];
    echo "</td></tr>";
    if ($type==1) {
        echo "<tr><td id=\"buybutton1\">";
        echo "</td><td id=\"buybutton2\">";
        $buttonnamearray=array();
        $buttonnamearray[0] = "buybutton";
        $buttonnamearray[1] = $i+1;
        $buybuttonname = implode("_", $buttonnamearray);
        $buttonnamesarray += $buybuttonname;
        echo "<form action=\"".$itemurl."\" method=\"post\">";
        echo "<input type=\"submit\" value=\"".$buybuttonname."\" name=\"buybutton\" class=\"buybutton\"/></form>";
        echo "</td></tr>";
    }
    echo "</table>";
    echo "</td></tr></table>";
    echo "</tr>";
    echo "</table>";
}

function savePurch () {
    if($_POST[gender]==NULL or $_POST[firstName]==NULL or $_POST[lastName]==NULL or $_POST[address]==NULL or $_POST[postalCode]==NULL or $_POST[postalOffice]==NULL or $_POST[country]==NULL or $_POST[purchases]==NULL) {
        echo "You did not fill out the necessary fields. Please do so in order to continue.";
    }
    else {
        $sqlconnect=mysql_connect('localhost', 'root', 'kissakala');
        $dbselect=mysql_select_db('theshop', $sqlconnect);
        if($sqlconnect and $dbselect) {
            $sqladd="INSERT INTO purchases (gender, firstName, lastName, address, postalCode, postalOffice, country, purchases) VALUES ('$_POST[gender]', '$_POST[firstName]', '$_POST[lastName]', '$_POST[address]', '$_POST[postalCode]', '$_POST[postalOffice]', '$_POST[country]', '$_POST[purchases]')";
            mysql_query($sqladd, $sqlconnect);
            mysql_close($sqlconnect);
        }
    }

}


function putFooter() {
    echo "<div id=\"footer\">&copy;2010 All rights reserved. Designed and developed by Ville and Pavlo.</div>";
}

function putCart() {
    echo "<td id=\"cartcol\"><div id=\"cart\">";
    echo $_COOKIE["boughttotal"];

    ## TABLE WITH CART BUTTONS
    echo "<table width=100% cellspacing=\"0\" cellpadding=\"0\" id=\"cartbuttons\"><tr><td id=\"gotobuttontable\">";
    echo "<form name=\"gotocart\" action=\"cart.php\" method=\"POST\"><input type=\"submit\" value=\"go to cart\" name=\"go_cart\" class=\"cartbutton\" /></form>";
    echo "</td>";
    echo "<td id=\"clearbuttontable\">";
    echo "<form name=\"cartbuttons\" action=\"cart.php\" method=\"POST\"><input type=\"submit\" value=\"clear cart\" name=\"clear_cart\" class=\"clearcartbutton\" onclick=\"java script:btnback_click()\"/>";
    echo "<input type=\"submit\" value=\"clear cart\" name=\"clear_cart\" class=\"clearcartbutton\" onclick=\"java script:btnback_click()\"/></form>";
    echo "</td>";
    echo "</tr></table>";
    ##

    echo "</div></td>";

}
function logout() {
    setcookie('boughttotal','',time()-3600);
}

function refreshfunc() {
    echo "BUT";
    $theLength=count($buttonnamesarray);
    echo "LEN";
    echo $theLength;
    for ($i = 0; $i < $theLength; $i++) {
        echo $buttonnamesarray[$i];
        echo $i;
    }
}
function alpha_numeric($str, $type=1) {
    if ($type==1) {
        #names
        #TODO name regexp
        return (preg_match("^[$()&|'{}*+?{\"]^", $str)) ? FALSE : TRUE;
    }
    else if ($type==2) {
        #town
        return (!preg_match("^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$^", $str)) ? FALSE : TRUE;
    }
    else if ($type==3) {
        #address
        #TODO street name regexp
        return (preg_match("[a-zA-z0-9]", $str)) ? FALSE : TRUE;

    }
}
?>
